home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / optparse.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  52.3 KB  |  1,523 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''A powerful, extensible, and easy-to-use option parser.
  5.  
  6. By Greg Ward <gward@python.net>
  7.  
  8. Originally distributed as Optik.
  9.  
  10. For support, use the optik-users@lists.sourceforge.net mailing list
  11. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  12. '''
  13. __version__ = '1.5.3'
  14. __all__ = [
  15.     'Option',
  16.     'make_option',
  17.     'SUPPRESS_HELP',
  18.     'SUPPRESS_USAGE',
  19.     'Values',
  20.     'OptionContainer',
  21.     'OptionGroup',
  22.     'OptionParser',
  23.     'HelpFormatter',
  24.     'IndentedHelpFormatter',
  25.     'TitledHelpFormatter',
  26.     'OptParseError',
  27.     'OptionError',
  28.     'OptionConflictError',
  29.     'OptionValueError',
  30.     'BadOptionError']
  31. __copyright__ = '\nCopyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.\nCopyright (c) 2002-2006 Python Software Foundation.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the author nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\nIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'
  32. import sys
  33. import os
  34. import types
  35. import textwrap
  36.  
  37. def _repr(self):
  38.     return '<%s at 0x%x: %s>' % (self.__class__.__name__, id(self), self)
  39.  
  40.  
  41. try:
  42.     from gettext import gettext
  43. except ImportError:
  44.     
  45.     def gettext(message):
  46.         return message
  47.  
  48.  
  49. _ = gettext
  50.  
  51. class OptParseError(Exception):
  52.     
  53.     def __init__(self, msg):
  54.         self.msg = msg
  55.  
  56.     
  57.     def __str__(self):
  58.         return self.msg
  59.  
  60.  
  61.  
  62. class OptionError(OptParseError):
  63.     '''
  64.     Raised if an Option instance is created with invalid or
  65.     inconsistent arguments.
  66.     '''
  67.     
  68.     def __init__(self, msg, option):
  69.         self.msg = msg
  70.         self.option_id = str(option)
  71.  
  72.     
  73.     def __str__(self):
  74.         if self.option_id:
  75.             return 'option %s: %s' % (self.option_id, self.msg)
  76.         return self.msg
  77.  
  78.  
  79.  
  80. class OptionConflictError(OptionError):
  81.     '''
  82.     Raised if conflicting options are added to an OptionParser.
  83.     '''
  84.     pass
  85.  
  86.  
  87. class OptionValueError(OptParseError):
  88.     '''
  89.     Raised if an invalid option value is encountered on the command
  90.     line.
  91.     '''
  92.     pass
  93.  
  94.  
  95. class BadOptionError(OptParseError):
  96.     '''
  97.     Raised if an invalid option is seen on the command line.
  98.     '''
  99.     
  100.     def __init__(self, opt_str):
  101.         self.opt_str = opt_str
  102.  
  103.     
  104.     def __str__(self):
  105.         return _('no such option: %s') % self.opt_str
  106.  
  107.  
  108.  
  109. class AmbiguousOptionError(BadOptionError):
  110.     '''
  111.     Raised if an ambiguous option is seen on the command line.
  112.     '''
  113.     
  114.     def __init__(self, opt_str, possibilities):
  115.         BadOptionError.__init__(self, opt_str)
  116.         self.possibilities = possibilities
  117.  
  118.     
  119.     def __str__(self):
  120.         return _('ambiguous option: %s (%s?)') % (self.opt_str, ', '.join(self.possibilities))
  121.  
  122.  
  123.  
  124. class HelpFormatter:
  125.     '''
  126.     Abstract base class for formatting option help.  OptionParser
  127.     instances should use one of the HelpFormatter subclasses for
  128.     formatting help; by default IndentedHelpFormatter is used.
  129.  
  130.     Instance attributes:
  131.       parser : OptionParser
  132.         the controlling OptionParser instance
  133.       indent_increment : int
  134.         the number of columns to indent per nesting level
  135.       max_help_position : int
  136.         the maximum starting column for option help text
  137.       help_position : int
  138.         the calculated starting column for option help text;
  139.         initially the same as the maximum
  140.       width : int
  141.         total number of columns for output (pass None to constructor for
  142.         this value to be taken from the $COLUMNS environment variable)
  143.       level : int
  144.         current indentation level
  145.       current_indent : int
  146.         current indentation level (in columns)
  147.       help_width : int
  148.         number of columns available for option help text (calculated)
  149.       default_tag : str
  150.         text to replace with each option\'s default value, "%default"
  151.         by default.  Set to false value to disable default value expansion.
  152.       option_strings : { Option : str }
  153.         maps Option instances to the snippet of help text explaining
  154.         the syntax of that option, e.g. "-h, --help" or
  155.         "-fFILE, --file=FILE"
  156.       _short_opt_fmt : str
  157.         format string controlling how short options with values are
  158.         printed in help text.  Must be either "%s%s" ("-fFILE") or
  159.         "%s %s" ("-f FILE"), because those are the two syntaxes that
  160.         Optik supports.
  161.       _long_opt_fmt : str
  162.         similar but for long options; must be either "%s %s" ("--file FILE")
  163.         or "%s=%s" ("--file=FILE").
  164.     '''
  165.     NO_DEFAULT_VALUE = 'none'
  166.     
  167.     def __init__(self, indent_increment, max_help_position, width, short_first):
  168.         self.parser = None
  169.         self.indent_increment = indent_increment
  170.         self.help_position = self.max_help_position = max_help_position
  171.         if width is None:
  172.             
  173.             try:
  174.                 width = int(os.environ['COLUMNS'])
  175.             except (KeyError, ValueError):
  176.                 width = 80
  177.  
  178.             width -= 2
  179.         
  180.         self.width = width
  181.         self.current_indent = 0
  182.         self.level = 0
  183.         self.help_width = None
  184.         self.short_first = short_first
  185.         self.default_tag = '%default'
  186.         self.option_strings = { }
  187.         self._short_opt_fmt = '%s %s'
  188.         self._long_opt_fmt = '%s=%s'
  189.  
  190.     
  191.     def set_parser(self, parser):
  192.         self.parser = parser
  193.  
  194.     
  195.     def set_short_opt_delimiter(self, delim):
  196.         if delim not in ('', ' '):
  197.             raise ValueError('invalid metavar delimiter for short options: %r' % delim)
  198.         delim not in ('', ' ')
  199.         self._short_opt_fmt = '%s' + delim + '%s'
  200.  
  201.     
  202.     def set_long_opt_delimiter(self, delim):
  203.         if delim not in ('=', ' '):
  204.             raise ValueError('invalid metavar delimiter for long options: %r' % delim)
  205.         delim not in ('=', ' ')
  206.         self._long_opt_fmt = '%s' + delim + '%s'
  207.  
  208.     
  209.     def indent(self):
  210.         self.current_indent += self.indent_increment
  211.         self.level += 1
  212.  
  213.     
  214.     def dedent(self):
  215.         self.current_indent -= self.indent_increment
  216.         if not self.current_indent >= 0:
  217.             raise AssertionError, 'Indent decreased below 0.'
  218.         self.level -= 1
  219.  
  220.     
  221.     def format_usage(self, usage):
  222.         raise NotImplementedError, 'subclasses must implement'
  223.  
  224.     
  225.     def format_heading(self, heading):
  226.         raise NotImplementedError, 'subclasses must implement'
  227.  
  228.     
  229.     def _format_text(self, text):
  230.         '''
  231.         Format a paragraph of free-form text for inclusion in the
  232.         help output at the current indentation level.
  233.         '''
  234.         text_width = self.width - self.current_indent
  235.         indent = ' ' * self.current_indent
  236.         return textwrap.fill(text, text_width, initial_indent = indent, subsequent_indent = indent)
  237.  
  238.     
  239.     def format_description(self, description):
  240.         if description:
  241.             return self._format_text(description) + '\n'
  242.         return ''
  243.  
  244.     
  245.     def format_epilog(self, epilog):
  246.         if epilog:
  247.             return '\n' + self._format_text(epilog) + '\n'
  248.         return ''
  249.  
  250.     
  251.     def expand_default(self, option):
  252.         if self.parser is None or not (self.default_tag):
  253.             return option.help
  254.         default_value = self.parser.defaults.get(option.dest)
  255.         if default_value is NO_DEFAULT or default_value is None:
  256.             default_value = self.NO_DEFAULT_VALUE
  257.         
  258.         return option.help.replace(self.default_tag, str(default_value))
  259.  
  260.     
  261.     def format_option(self, option):
  262.         result = []
  263.         opts = self.option_strings[option]
  264.         opt_width = self.help_position - self.current_indent - 2
  265.         if len(opts) > opt_width:
  266.             opts = '%*s%s\n' % (self.current_indent, '', opts)
  267.             indent_first = self.help_position
  268.         else:
  269.             opts = '%*s%-*s  ' % (self.current_indent, '', opt_width, opts)
  270.             indent_first = 0
  271.         result.append(opts)
  272.         if option.help:
  273.             help_text = self.expand_default(option)
  274.             help_lines = textwrap.wrap(help_text, self.help_width)
  275.             result.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  276.             []([ '%*s%s\n' % (self.help_position, '', line) for line in help_lines[1:] ])
  277.         elif opts[-1] != '\n':
  278.             result.append('\n')
  279.         
  280.         return ''.join(result)
  281.  
  282.     
  283.     def store_option_strings(self, parser):
  284.         self.indent()
  285.         max_len = 0
  286.         for opt in parser.option_list:
  287.             strings = self.format_option_strings(opt)
  288.             self.option_strings[opt] = strings
  289.             max_len = max(max_len, len(strings) + self.current_indent)
  290.         
  291.         self.indent()
  292.         for group in parser.option_groups:
  293.             for opt in group.option_list:
  294.                 strings = self.format_option_strings(opt)
  295.                 self.option_strings[opt] = strings
  296.                 max_len = max(max_len, len(strings) + self.current_indent)
  297.             
  298.         
  299.         self.dedent()
  300.         self.dedent()
  301.         self.help_position = min(max_len + 2, self.max_help_position)
  302.         self.help_width = self.width - self.help_position
  303.  
  304.     
  305.     def format_option_strings(self, option):
  306.         '''Return a comma-separated list of option strings & metavariables.'''
  307.         return ', '.join(opts)
  308.  
  309.  
  310.  
  311. class IndentedHelpFormatter(HelpFormatter):
  312.     '''Format help with indented section bodies.
  313.     '''
  314.     
  315.     def __init__(self, indent_increment = 2, max_help_position = 24, width = None, short_first = 1):
  316.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  317.  
  318.     
  319.     def format_usage(self, usage):
  320.         return _('Usage: %s\n') % usage
  321.  
  322.     
  323.     def format_heading(self, heading):
  324.         return '%*s%s:\n' % (self.current_indent, '', heading)
  325.  
  326.  
  327.  
  328. class TitledHelpFormatter(HelpFormatter):
  329.     '''Format help with underlined section headers.
  330.     '''
  331.     
  332.     def __init__(self, indent_increment = 0, max_help_position = 24, width = None, short_first = 0):
  333.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  334.  
  335.     
  336.     def format_usage(self, usage):
  337.         return '%s  %s\n' % (self.format_heading(_('Usage')), usage)
  338.  
  339.     
  340.     def format_heading(self, heading):
  341.         return '%s\n%s\n' % (heading, '=-'[self.level] * len(heading))
  342.  
  343.  
  344.  
  345. def _parse_num(val, type):
  346.     if val[:2].lower() == '0x':
  347.         radix = 16
  348.     elif val[:2].lower() == '0b':
  349.         radix = 2
  350.         if not val[2:]:
  351.             pass
  352.         val = '0'
  353.     elif val[:1] == '0':
  354.         radix = 8
  355.     else:
  356.         radix = 10
  357.     return type(val, radix)
  358.  
  359.  
  360. def _parse_int(val):
  361.     return _parse_num(val, int)
  362.  
  363.  
  364. def _parse_long(val):
  365.     return _parse_num(val, long)
  366.  
  367. _builtin_cvt = {
  368.     'int': (_parse_int, _('integer')),
  369.     'long': (_parse_long, _('long integer')),
  370.     'float': (float, _('floating-point')),
  371.     'complex': (complex, _('complex')) }
  372.  
  373. def check_builtin(option, opt, value):
  374.     (cvt, what) = _builtin_cvt[option.type]
  375.     
  376.     try:
  377.         return cvt(value)
  378.     except ValueError:
  379.         raise OptionValueError(_('option %s: invalid %s value: %r') % (opt, what, value))
  380.  
  381.  
  382.  
  383. def check_choice(option, opt, value):
  384.     if value in option.choices:
  385.         return value
  386.     choices = ', '.join(map(repr, option.choices))
  387.     raise OptionValueError(_('option %s: invalid choice: %r (choose from %s)') % (opt, value, choices))
  388.  
  389. NO_DEFAULT = ('NO', 'DEFAULT')
  390.  
  391. class Option:
  392.     '''
  393.     Instance attributes:
  394.       _short_opts : [string]
  395.       _long_opts : [string]
  396.  
  397.       action : string
  398.       type : string
  399.       dest : string
  400.       default : any
  401.       nargs : int
  402.       const : any
  403.       choices : [string]
  404.       callback : function
  405.       callback_args : (any*)
  406.       callback_kwargs : { string : any }
  407.       help : string
  408.       metavar : string
  409.     '''
  410.     ATTRS = [
  411.         'action',
  412.         'type',
  413.         'dest',
  414.         'default',
  415.         'nargs',
  416.         'const',
  417.         'choices',
  418.         'callback',
  419.         'callback_args',
  420.         'callback_kwargs',
  421.         'help',
  422.         'metavar']
  423.     ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count', 'callback', 'help', 'version')
  424.     STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count')
  425.     TYPED_ACTIONS = ('store', 'append', 'callback')
  426.     ALWAYS_TYPED_ACTIONS = ('store', 'append')
  427.     CONST_ACTIONS = ('store_const', 'append_const')
  428.     TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
  429.     TYPE_CHECKER = {
  430.         'int': check_builtin,
  431.         'long': check_builtin,
  432.         'float': check_builtin,
  433.         'complex': check_builtin,
  434.         'choice': check_choice }
  435.     CHECK_METHODS = None
  436.     
  437.     def __init__(self, *opts, **attrs):
  438.         self._short_opts = []
  439.         self._long_opts = []
  440.         opts = self._check_opt_strings(opts)
  441.         self._set_opt_strings(opts)
  442.         self._set_attrs(attrs)
  443.         for checker in self.CHECK_METHODS:
  444.             checker(self)
  445.         
  446.  
  447.     
  448.     def _check_opt_strings(self, opts):
  449.         opts = filter(None, opts)
  450.         if not opts:
  451.             raise TypeError('at least one option string must be supplied')
  452.         opts
  453.         return opts
  454.  
  455.     
  456.     def _set_opt_strings(self, opts):
  457.         for opt in opts:
  458.             if len(opt) < 2:
  459.                 raise OptionError('invalid option string %r: must be at least two characters long' % opt, self)
  460.             len(opt) < 2
  461.             if len(opt) == 2:
  462.                 if not opt[0] == '-' and opt[1] != '-':
  463.                     raise OptionError('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt, self)
  464.                 opt[1] != '-'
  465.                 self._short_opts.append(opt)
  466.                 continue
  467.             if not opt[0:2] == '--' and opt[2] != '-':
  468.                 raise OptionError('invalid long option string %r: must start with --, followed by non-dash' % opt, self)
  469.             opt[2] != '-'
  470.             self._long_opts.append(opt)
  471.         
  472.  
  473.     
  474.     def _set_attrs(self, attrs):
  475.         for attr in self.ATTRS:
  476.             if attr in attrs:
  477.                 setattr(self, attr, attrs[attr])
  478.                 del attrs[attr]
  479.                 continue
  480.             if attr == 'default':
  481.                 setattr(self, attr, NO_DEFAULT)
  482.                 continue
  483.             setattr(self, attr, None)
  484.         
  485.         if attrs:
  486.             attrs = attrs.keys()
  487.             attrs.sort()
  488.             raise OptionError('invalid keyword arguments: %s' % ', '.join(attrs), self)
  489.         attrs
  490.  
  491.     
  492.     def _check_action(self):
  493.         if self.action is None:
  494.             self.action = 'store'
  495.         elif self.action not in self.ACTIONS:
  496.             raise OptionError('invalid action: %r' % self.action, self)
  497.         
  498.  
  499.     
  500.     def _check_type(self):
  501.         if self.type is None:
  502.             if self.action in self.ALWAYS_TYPED_ACTIONS:
  503.                 if self.choices is not None:
  504.                     self.type = 'choice'
  505.                 else:
  506.                     self.type = 'string'
  507.             
  508.         else:
  509.             import __builtin__
  510.             if (type(self.type) is types.TypeType or hasattr(self.type, '__name__')) and getattr(__builtin__, self.type.__name__, None) is self.type:
  511.                 self.type = self.type.__name__
  512.             
  513.             if self.type == 'str':
  514.                 self.type = 'string'
  515.             
  516.             if self.type not in self.TYPES:
  517.                 raise OptionError('invalid option type: %r' % self.type, self)
  518.             self.type not in self.TYPES
  519.             if self.action not in self.TYPED_ACTIONS:
  520.                 raise OptionError('must not supply a type for action %r' % self.action, self)
  521.             self.action not in self.TYPED_ACTIONS
  522.  
  523.     
  524.     def _check_choice(self):
  525.         if self.type == 'choice':
  526.             if self.choices is None:
  527.                 raise OptionError("must supply a list of choices for type 'choice'", self)
  528.             self.choices is None
  529.             if type(self.choices) not in (types.TupleType, types.ListType):
  530.                 raise OptionError("choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self)
  531.             type(self.choices) not in (types.TupleType, types.ListType)
  532.         elif self.choices is not None:
  533.             raise OptionError('must not supply choices for type %r' % self.type, self)
  534.         
  535.  
  536.     
  537.     def _check_dest(self):
  538.         if not self.action in self.STORE_ACTIONS:
  539.             pass
  540.         takes_value = self.type is not None
  541.         if self.dest is None and takes_value:
  542.             if self._long_opts:
  543.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  544.             else:
  545.                 self.dest = self._short_opts[0][1]
  546.         
  547.  
  548.     
  549.     def _check_const(self):
  550.         if self.action not in self.CONST_ACTIONS and self.const is not None:
  551.             raise OptionError("'const' must not be supplied for action %r" % self.action, self)
  552.         self.const is not None
  553.  
  554.     
  555.     def _check_nargs(self):
  556.         if self.action in self.TYPED_ACTIONS:
  557.             if self.nargs is None:
  558.                 self.nargs = 1
  559.             
  560.         elif self.nargs is not None:
  561.             raise OptionError("'nargs' must not be supplied for action %r" % self.action, self)
  562.         
  563.  
  564.     
  565.     def _check_callback(self):
  566.         if self.action == 'callback':
  567.             if not hasattr(self.callback, '__call__'):
  568.                 raise OptionError('callback not callable: %r' % self.callback, self)
  569.             hasattr(self.callback, '__call__')
  570.             if self.callback_args is not None and type(self.callback_args) is not types.TupleType:
  571.                 raise OptionError('callback_args, if supplied, must be a tuple: not %r' % self.callback_args, self)
  572.             type(self.callback_args) is not types.TupleType
  573.             if self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType:
  574.                 raise OptionError('callback_kwargs, if supplied, must be a dict: not %r' % self.callback_kwargs, self)
  575.             type(self.callback_kwargs) is not types.DictType
  576.         elif self.callback is not None:
  577.             raise OptionError('callback supplied (%r) for non-callback option' % self.callback, self)
  578.         
  579.         if self.callback_args is not None:
  580.             raise OptionError('callback_args supplied for non-callback option', self)
  581.         self.callback_args is not None
  582.         if self.callback_kwargs is not None:
  583.             raise OptionError('callback_kwargs supplied for non-callback option', self)
  584.         self.callback_kwargs is not None
  585.  
  586.     CHECK_METHODS = [
  587.         _check_action,
  588.         _check_type,
  589.         _check_choice,
  590.         _check_dest,
  591.         _check_const,
  592.         _check_nargs,
  593.         _check_callback]
  594.     
  595.     def __str__(self):
  596.         return '/'.join(self._short_opts + self._long_opts)
  597.  
  598.     __repr__ = _repr
  599.     
  600.     def takes_value(self):
  601.         return self.type is not None
  602.  
  603.     
  604.     def get_opt_string(self):
  605.         if self._long_opts:
  606.             return self._long_opts[0]
  607.         return self._short_opts[0]
  608.  
  609.     
  610.     def check_value(self, opt, value):
  611.         checker = self.TYPE_CHECKER.get(self.type)
  612.         if checker is None:
  613.             return value
  614.         return checker(self, opt, value)
  615.  
  616.     
  617.     def convert_value(self, opt, value):
  618.         if value is not None:
  619.             if self.nargs == 1:
  620.                 return self.check_value(opt, value)
  621.             return []([ self.check_value(opt, v) for v in value ])
  622.         value is not None
  623.  
  624.     
  625.     def process(self, opt, value, values, parser):
  626.         value = self.convert_value(opt, value)
  627.         return self.take_action(self.action, self.dest, opt, value, values, parser)
  628.  
  629.     
  630.     def take_action(self, action, dest, opt, value, values, parser):
  631.         if action == 'store':
  632.             setattr(values, dest, value)
  633.         elif action == 'store_const':
  634.             setattr(values, dest, self.const)
  635.         elif action == 'store_true':
  636.             setattr(values, dest, True)
  637.         elif action == 'store_false':
  638.             setattr(values, dest, False)
  639.         elif action == 'append':
  640.             values.ensure_value(dest, []).append(value)
  641.         elif action == 'append_const':
  642.             values.ensure_value(dest, []).append(self.const)
  643.         elif action == 'count':
  644.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  645.         elif action == 'callback':
  646.             if not self.callback_args:
  647.                 pass
  648.             args = ()
  649.             if not self.callback_kwargs:
  650.                 pass
  651.             kwargs = { }
  652.             self.callback(self, opt, value, parser, *args, **kwargs)
  653.         elif action == 'help':
  654.             parser.print_help()
  655.             parser.exit()
  656.         elif action == 'version':
  657.             parser.print_version()
  658.             parser.exit()
  659.         else:
  660.             raise RuntimeError, 'unknown action %r' % self.action
  661.         return action == 'store'
  662.  
  663.  
  664. SUPPRESS_HELP = 'SUPPRESS' + 'HELP'
  665. SUPPRESS_USAGE = 'SUPPRESS' + 'USAGE'
  666.  
  667. try:
  668.     basestring
  669. except NameError:
  670.     
  671.     def isbasestring(x):
  672.         return isinstance(x, (types.StringType, types.UnicodeType))
  673.  
  674.  
  675.  
  676. def isbasestring(x):
  677.     return isinstance(x, basestring)
  678.  
  679.  
  680. class Values:
  681.     
  682.     def __init__(self, defaults = None):
  683.         if defaults:
  684.             for attr, val in defaults.items():
  685.                 setattr(self, attr, val)
  686.             
  687.         
  688.  
  689.     
  690.     def __str__(self):
  691.         return str(self.__dict__)
  692.  
  693.     __repr__ = _repr
  694.     
  695.     def __cmp__(self, other):
  696.         if isinstance(other, Values):
  697.             return cmp(self.__dict__, other.__dict__)
  698.         if isinstance(other, types.DictType):
  699.             return cmp(self.__dict__, other)
  700.         return -1
  701.  
  702.     
  703.     def _update_careful(self, dict):
  704.         '''
  705.         Update the option values from an arbitrary dictionary, but only
  706.         use keys from dict that already have a corresponding attribute
  707.         in self.  Any keys in dict without a corresponding attribute
  708.         are silently ignored.
  709.         '''
  710.         for attr in dir(self):
  711.             if attr in dict:
  712.                 dval = dict[attr]
  713.                 if dval is not None:
  714.                     setattr(self, attr, dval)
  715.                 
  716.             dval is not None
  717.         
  718.  
  719.     
  720.     def _update_loose(self, dict):
  721.         '''
  722.         Update the option values from an arbitrary dictionary,
  723.         using all keys from the dictionary regardless of whether
  724.         they have a corresponding attribute in self or not.
  725.         '''
  726.         self.__dict__.update(dict)
  727.  
  728.     
  729.     def _update(self, dict, mode):
  730.         if mode == 'careful':
  731.             self._update_careful(dict)
  732.         elif mode == 'loose':
  733.             self._update_loose(dict)
  734.         else:
  735.             raise ValueError, 'invalid update mode: %r' % mode
  736.         return mode == 'careful'
  737.  
  738.     
  739.     def read_module(self, modname, mode = 'careful'):
  740.         __import__(modname)
  741.         mod = sys.modules[modname]
  742.         self._update(vars(mod), mode)
  743.  
  744.     
  745.     def read_file(self, filename, mode = 'careful'):
  746.         vars = { }
  747.         execfile(filename, vars)
  748.         self._update(vars, mode)
  749.  
  750.     
  751.     def ensure_value(self, attr, value):
  752.         if not hasattr(self, attr) or getattr(self, attr) is None:
  753.             setattr(self, attr, value)
  754.         
  755.         return getattr(self, attr)
  756.  
  757.  
  758.  
  759. class OptionContainer:
  760.     '''
  761.     Abstract base class.
  762.  
  763.     Class attributes:
  764.       standard_option_list : [Option]
  765.         list of standard options that will be accepted by all instances
  766.         of this parser class (intended to be overridden by subclasses).
  767.  
  768.     Instance attributes:
  769.       option_list : [Option]
  770.         the list of Option objects contained by this OptionContainer
  771.       _short_opt : { string : Option }
  772.         dictionary mapping short option strings, eg. "-f" or "-X",
  773.         to the Option instances that implement them.  If an Option
  774.         has multiple short option strings, it will appears in this
  775.         dictionary multiple times. [1]
  776.       _long_opt : { string : Option }
  777.         dictionary mapping long option strings, eg. "--file" or
  778.         "--exclude", to the Option instances that implement them.
  779.         Again, a given Option can occur multiple times in this
  780.         dictionary. [1]
  781.       defaults : { string : any }
  782.         dictionary mapping option destination names to default
  783.         values for each destination [1]
  784.  
  785.     [1] These mappings are common to (shared by) all components of the
  786.         controlling OptionParser, where they are initially created.
  787.  
  788.     '''
  789.     
  790.     def __init__(self, option_class, conflict_handler, description):
  791.         self._create_option_list()
  792.         self.option_class = option_class
  793.         self.set_conflict_handler(conflict_handler)
  794.         self.set_description(description)
  795.  
  796.     
  797.     def _create_option_mappings(self):
  798.         self._short_opt = { }
  799.         self._long_opt = { }
  800.         self.defaults = { }
  801.  
  802.     
  803.     def _share_option_mappings(self, parser):
  804.         self._short_opt = parser._short_opt
  805.         self._long_opt = parser._long_opt
  806.         self.defaults = parser.defaults
  807.  
  808.     
  809.     def set_conflict_handler(self, handler):
  810.         if handler not in ('error', 'resolve'):
  811.             raise ValueError, 'invalid conflict_resolution value %r' % handler
  812.         handler not in ('error', 'resolve')
  813.         self.conflict_handler = handler
  814.  
  815.     
  816.     def set_description(self, description):
  817.         self.description = description
  818.  
  819.     
  820.     def get_description(self):
  821.         return self.description
  822.  
  823.     
  824.     def destroy(self):
  825.         '''see OptionParser.destroy().'''
  826.         del self._short_opt
  827.         del self._long_opt
  828.         del self.defaults
  829.  
  830.     
  831.     def _check_conflict(self, option):
  832.         conflict_opts = []
  833.         for opt in option._short_opts:
  834.             if opt in self._short_opt:
  835.                 conflict_opts.append((opt, self._short_opt[opt]))
  836.                 continue
  837.         
  838.         for opt in option._long_opts:
  839.             if opt in self._long_opt:
  840.                 conflict_opts.append((opt, self._long_opt[opt]))
  841.                 continue
  842.         
  843.         if conflict_opts:
  844.             handler = self.conflict_handler
  845.             if handler == 'error':
  846.                 raise ', '.join([] % []([ co[0] for co in conflict_opts ]), option)
  847.             handler == 'error'
  848.             if handler == 'resolve':
  849.                 for opt, c_option in conflict_opts:
  850.                     if opt.startswith('--'):
  851.                         c_option._long_opts.remove(opt)
  852.                         del self._long_opt[opt]
  853.                     else:
  854.                         c_option._short_opts.remove(opt)
  855.                         del self._short_opt[opt]
  856.                     if not c_option._short_opts or c_option._long_opts:
  857.                         c_option.container.option_list.remove(c_option)
  858.                         continue
  859.                 
  860.             
  861.         
  862.  
  863.     
  864.     def add_option(self, *args, **kwargs):
  865.         '''add_option(Option)
  866.            add_option(opt_str, ..., kwarg=val, ...)
  867.         '''
  868.         if type(args[0]) in types.StringTypes:
  869.             option = self.option_class(*args, **kwargs)
  870.         elif len(args) == 1 and not kwargs:
  871.             option = args[0]
  872.             if not isinstance(option, Option):
  873.                 raise TypeError, 'not an Option instance: %r' % option
  874.             isinstance(option, Option)
  875.         else:
  876.             raise TypeError, 'invalid arguments'
  877.         (not kwargs)._check_conflict(option)
  878.         self.option_list.append(option)
  879.         option.container = self
  880.         for opt in option._short_opts:
  881.             self._short_opt[opt] = option
  882.         
  883.         for opt in option._long_opts:
  884.             self._long_opt[opt] = option
  885.         
  886.         if option.dest is not None:
  887.             if option.default is not NO_DEFAULT:
  888.                 self.defaults[option.dest] = option.default
  889.             elif option.dest not in self.defaults:
  890.                 self.defaults[option.dest] = None
  891.             
  892.         
  893.         return option
  894.  
  895.     
  896.     def add_options(self, option_list):
  897.         for option in option_list:
  898.             self.add_option(option)
  899.         
  900.  
  901.     
  902.     def get_option(self, opt_str):
  903.         if not self._short_opt.get(opt_str):
  904.             pass
  905.         return self._long_opt.get(opt_str)
  906.  
  907.     
  908.     def has_option(self, opt_str):
  909.         if not opt_str in self._short_opt:
  910.             pass
  911.         return opt_str in self._long_opt
  912.  
  913.     
  914.     def remove_option(self, opt_str):
  915.         option = self._short_opt.get(opt_str)
  916.         if option is None:
  917.             option = self._long_opt.get(opt_str)
  918.         
  919.         if option is None:
  920.             raise ValueError('no such option %r' % opt_str)
  921.         option is None
  922.         for opt in option._short_opts:
  923.             del self._short_opt[opt]
  924.         
  925.         for opt in option._long_opts:
  926.             del self._long_opt[opt]
  927.         
  928.         option.container.option_list.remove(option)
  929.  
  930.     
  931.     def format_option_help(self, formatter):
  932.         if not self.option_list:
  933.             return ''
  934.         result = []
  935.         for option in self.option_list:
  936.             if option.help is not SUPPRESS_HELP:
  937.                 result.append(formatter.format_option(option))
  938.                 continue
  939.             self.option_list
  940.         
  941.         return ''.join(result)
  942.  
  943.     
  944.     def format_description(self, formatter):
  945.         return formatter.format_description(self.get_description())
  946.  
  947.     
  948.     def format_help(self, formatter):
  949.         result = []
  950.         if self.description:
  951.             result.append(self.format_description(formatter))
  952.         
  953.         if self.option_list:
  954.             result.append(self.format_option_help(formatter))
  955.         
  956.         return '\n'.join(result)
  957.  
  958.  
  959.  
  960. class OptionGroup(OptionContainer):
  961.     
  962.     def __init__(self, parser, title, description = None):
  963.         self.parser = parser
  964.         OptionContainer.__init__(self, parser.option_class, parser.conflict_handler, description)
  965.         self.title = title
  966.  
  967.     
  968.     def _create_option_list(self):
  969.         self.option_list = []
  970.         self._share_option_mappings(self.parser)
  971.  
  972.     
  973.     def set_title(self, title):
  974.         self.title = title
  975.  
  976.     
  977.     def destroy(self):
  978.         '''see OptionParser.destroy().'''
  979.         OptionContainer.destroy(self)
  980.         del self.option_list
  981.  
  982.     
  983.     def format_help(self, formatter):
  984.         result = formatter.format_heading(self.title)
  985.         formatter.indent()
  986.         result += OptionContainer.format_help(self, formatter)
  987.         formatter.dedent()
  988.         return result
  989.  
  990.  
  991.  
  992. class OptionParser(OptionContainer):
  993.     '''
  994.     Class attributes:
  995.       standard_option_list : [Option]
  996.         list of standard options that will be accepted by all instances
  997.         of this parser class (intended to be overridden by subclasses).
  998.  
  999.     Instance attributes:
  1000.       usage : string
  1001.         a usage string for your program.  Before it is displayed
  1002.         to the user, "%prog" will be expanded to the name of
  1003.         your program (self.prog or os.path.basename(sys.argv[0])).
  1004.       prog : string
  1005.         the name of the current program (to override
  1006.         os.path.basename(sys.argv[0])).
  1007.       epilog : string
  1008.         paragraph of help text to print after option help
  1009.  
  1010.       option_groups : [OptionGroup]
  1011.         list of option groups in this parser (option groups are
  1012.         irrelevant for parsing the command-line, but very useful
  1013.         for generating help)
  1014.  
  1015.       allow_interspersed_args : bool = true
  1016.         if true, positional arguments may be interspersed with options.
  1017.         Assuming -a and -b each take a single argument, the command-line
  1018.           -ablah foo bar -bboo baz
  1019.         will be interpreted the same as
  1020.           -ablah -bboo -- foo bar baz
  1021.         If this flag were false, that command line would be interpreted as
  1022.           -ablah -- foo bar -bboo baz
  1023.         -- ie. we stop processing options as soon as we see the first
  1024.         non-option argument.  (This is the tradition followed by
  1025.         Python\'s getopt module, Perl\'s Getopt::Std, and other argument-
  1026.         parsing libraries, but it is generally annoying to users.)
  1027.  
  1028.       process_default_values : bool = true
  1029.         if true, option default values are processed similarly to option
  1030.         values from the command line: that is, they are passed to the
  1031.         type-checking function for the option\'s type (as long as the
  1032.         default value is a string).  (This really only matters if you
  1033.         have defined custom types; see SF bug #955889.)  Set it to false
  1034.         to restore the behaviour of Optik 1.4.1 and earlier.
  1035.  
  1036.       rargs : [string]
  1037.         the argument list currently being parsed.  Only set when
  1038.         parse_args() is active, and continually trimmed down as
  1039.         we consume arguments.  Mainly there for the benefit of
  1040.         callback options.
  1041.       largs : [string]
  1042.         the list of leftover arguments that we have skipped while
  1043.         parsing options.  If allow_interspersed_args is false, this
  1044.         list is always empty.
  1045.       values : Values
  1046.         the set of option values currently being accumulated.  Only
  1047.         set when parse_args() is active.  Also mainly for callbacks.
  1048.  
  1049.     Because of the \'rargs\', \'largs\', and \'values\' attributes,
  1050.     OptionParser is not thread-safe.  If, for some perverse reason, you
  1051.     need to parse command-line arguments simultaneously in different
  1052.     threads, use different OptionParser instances.
  1053.  
  1054.     '''
  1055.     standard_option_list = []
  1056.     
  1057.     def __init__(self, usage = None, option_list = None, option_class = Option, version = None, conflict_handler = 'error', description = None, formatter = None, add_help_option = True, prog = None, epilog = None):
  1058.         OptionContainer.__init__(self, option_class, conflict_handler, description)
  1059.         self.set_usage(usage)
  1060.         self.prog = prog
  1061.         self.version = version
  1062.         self.allow_interspersed_args = True
  1063.         self.process_default_values = True
  1064.         if formatter is None:
  1065.             formatter = IndentedHelpFormatter()
  1066.         
  1067.         self.formatter = formatter
  1068.         self.formatter.set_parser(self)
  1069.         self.epilog = epilog
  1070.         self._populate_option_list(option_list, add_help = add_help_option)
  1071.         self._init_parsing_state()
  1072.  
  1073.     
  1074.     def destroy(self):
  1075.         '''
  1076.         Declare that you are done with this OptionParser.  This cleans up
  1077.         reference cycles so the OptionParser (and all objects referenced by
  1078.         it) can be garbage-collected promptly.  After calling destroy(), the
  1079.         OptionParser is unusable.
  1080.         '''
  1081.         OptionContainer.destroy(self)
  1082.         for group in self.option_groups:
  1083.             group.destroy()
  1084.         
  1085.         del self.option_list
  1086.         del self.option_groups
  1087.         del self.formatter
  1088.  
  1089.     
  1090.     def _create_option_list(self):
  1091.         self.option_list = []
  1092.         self.option_groups = []
  1093.         self._create_option_mappings()
  1094.  
  1095.     
  1096.     def _add_help_option(self):
  1097.         self.add_option('-h', '--help', action = 'help', help = _('show this help message and exit'))
  1098.  
  1099.     
  1100.     def _add_version_option(self):
  1101.         self.add_option('--version', action = 'version', help = _("show program's version number and exit"))
  1102.  
  1103.     
  1104.     def _populate_option_list(self, option_list, add_help = True):
  1105.         if self.standard_option_list:
  1106.             self.add_options(self.standard_option_list)
  1107.         
  1108.         if option_list:
  1109.             self.add_options(option_list)
  1110.         
  1111.         if self.version:
  1112.             self._add_version_option()
  1113.         
  1114.         if add_help:
  1115.             self._add_help_option()
  1116.         
  1117.  
  1118.     
  1119.     def _init_parsing_state(self):
  1120.         self.rargs = None
  1121.         self.largs = None
  1122.         self.values = None
  1123.  
  1124.     
  1125.     def set_usage(self, usage):
  1126.         if usage is None:
  1127.             self.usage = _('%prog [options]')
  1128.         elif usage is SUPPRESS_USAGE:
  1129.             self.usage = None
  1130.         elif usage.lower().startswith('usage: '):
  1131.             self.usage = usage[7:]
  1132.         else:
  1133.             self.usage = usage
  1134.  
  1135.     
  1136.     def enable_interspersed_args(self):
  1137.         '''Set parsing to not stop on the first non-option, allowing
  1138.         interspersing switches with command arguments. This is the
  1139.         default behavior. See also disable_interspersed_args() and the
  1140.         class documentation description of the attribute
  1141.         allow_interspersed_args.'''
  1142.         self.allow_interspersed_args = True
  1143.  
  1144.     
  1145.     def disable_interspersed_args(self):
  1146.         """Set parsing to stop on the first non-option. Use this if
  1147.         you have a command processor which runs another command that
  1148.         has options of its own and you want to make sure these options
  1149.         don't get confused.
  1150.         """
  1151.         self.allow_interspersed_args = False
  1152.  
  1153.     
  1154.     def set_process_default_values(self, process):
  1155.         self.process_default_values = process
  1156.  
  1157.     
  1158.     def set_default(self, dest, value):
  1159.         self.defaults[dest] = value
  1160.  
  1161.     
  1162.     def set_defaults(self, **kwargs):
  1163.         self.defaults.update(kwargs)
  1164.  
  1165.     
  1166.     def _get_all_options(self):
  1167.         options = self.option_list[:]
  1168.         for group in self.option_groups:
  1169.             options.extend(group.option_list)
  1170.         
  1171.         return options
  1172.  
  1173.     
  1174.     def get_default_values(self):
  1175.         if not self.process_default_values:
  1176.             return Values(self.defaults)
  1177.         defaults = self.defaults.copy()
  1178.         for option in self._get_all_options():
  1179.             default = defaults.get(option.dest)
  1180.             if isbasestring(default):
  1181.                 opt_str = option.get_opt_string()
  1182.                 defaults[option.dest] = option.check_value(opt_str, default)
  1183.                 continue
  1184.             self.process_default_values
  1185.         
  1186.         return Values(defaults)
  1187.  
  1188.     
  1189.     def add_option_group(self, *args, **kwargs):
  1190.         if type(args[0]) is types.StringType:
  1191.             group = OptionGroup(self, *args, **kwargs)
  1192.         elif len(args) == 1 and not kwargs:
  1193.             group = args[0]
  1194.             if not isinstance(group, OptionGroup):
  1195.                 raise TypeError, 'not an OptionGroup instance: %r' % group
  1196.             isinstance(group, OptionGroup)
  1197.             if group.parser is not self:
  1198.                 raise ValueError, 'invalid OptionGroup (wrong parser)'
  1199.             group.parser is not self
  1200.         else:
  1201.             raise TypeError, 'invalid arguments'
  1202.         (not kwargs).option_groups.append(group)
  1203.         return group
  1204.  
  1205.     
  1206.     def get_option_group(self, opt_str):
  1207.         if not self._short_opt.get(opt_str):
  1208.             pass
  1209.         option = self._long_opt.get(opt_str)
  1210.         if option and option.container is not self:
  1211.             return option.container
  1212.  
  1213.     
  1214.     def _get_args(self, args):
  1215.         if args is None:
  1216.             return sys.argv[1:]
  1217.         return args[:]
  1218.  
  1219.     
  1220.     def parse_args(self, args = None, values = None):
  1221.         """
  1222.         parse_args(args : [string] = sys.argv[1:],
  1223.                    values : Values = None)
  1224.         -> (values : Values, args : [string])
  1225.  
  1226.         Parse the command-line options found in 'args' (default:
  1227.         sys.argv[1:]).  Any errors result in a call to 'error()', which
  1228.         by default prints the usage message to stderr and calls
  1229.         sys.exit() with an error message.  On success returns a pair
  1230.         (values, args) where 'values' is an Values instance (with all
  1231.         your option values) and 'args' is the list of arguments left
  1232.         over after parsing options.
  1233.         """
  1234.         rargs = self._get_args(args)
  1235.         if values is None:
  1236.             values = self.get_default_values()
  1237.         
  1238.         self.rargs = rargs
  1239.         self.largs = largs = []
  1240.         self.values = values
  1241.         
  1242.         try:
  1243.             stop = self._process_args(largs, rargs, values)
  1244.         except (BadOptionError, OptionValueError):
  1245.             err = None
  1246.             self.error(str(err))
  1247.  
  1248.         args = largs + rargs
  1249.         return self.check_values(values, args)
  1250.  
  1251.     
  1252.     def check_values(self, values, args):
  1253.         '''
  1254.         check_values(values : Values, args : [string])
  1255.         -> (values : Values, args : [string])
  1256.  
  1257.         Check that the supplied option values and leftover arguments are
  1258.         valid.  Returns the option values and leftover arguments
  1259.         (possibly adjusted, possibly completely new -- whatever you
  1260.         like).  Default implementation just returns the passed-in
  1261.         values; subclasses may override as desired.
  1262.         '''
  1263.         return (values, args)
  1264.  
  1265.     
  1266.     def _process_args(self, largs, rargs, values):
  1267.         """_process_args(largs : [string],
  1268.                          rargs : [string],
  1269.                          values : Values)
  1270.  
  1271.         Process command-line arguments and populate 'values', consuming
  1272.         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
  1273.         false, stop at the first non-option argument.  If true, accumulate any
  1274.         interspersed non-option arguments in 'largs'.
  1275.         """
  1276.         while rargs:
  1277.             arg = rargs[0]
  1278.             if arg == '--':
  1279.                 del rargs[0]
  1280.                 return None
  1281.             if arg[0:2] == '--':
  1282.                 self._process_long_opt(rargs, values)
  1283.                 continue
  1284.             arg == '--'
  1285.             if arg[:1] == '-' and len(arg) > 1:
  1286.                 self._process_short_opts(rargs, values)
  1287.                 continue
  1288.             if self.allow_interspersed_args:
  1289.                 largs.append(arg)
  1290.                 del rargs[0]
  1291.                 continue
  1292.             return None
  1293.  
  1294.     
  1295.     def _match_long_opt(self, opt):
  1296.         """_match_long_opt(opt : string) -> string
  1297.  
  1298.         Determine which long option string 'opt' matches, ie. which one
  1299.         it is an unambiguous abbrevation for.  Raises BadOptionError if
  1300.         'opt' doesn't unambiguously match any long option string.
  1301.         """
  1302.         return _match_abbrev(opt, self._long_opt)
  1303.  
  1304.     
  1305.     def _process_long_opt(self, rargs, values):
  1306.         arg = rargs.pop(0)
  1307.         if '=' in arg:
  1308.             (opt, next_arg) = arg.split('=', 1)
  1309.             rargs.insert(0, next_arg)
  1310.             had_explicit_value = True
  1311.         else:
  1312.             opt = arg
  1313.             had_explicit_value = False
  1314.         opt = self._match_long_opt(opt)
  1315.         option = self._long_opt[opt]
  1316.         if option.takes_value():
  1317.             nargs = option.nargs
  1318.             if len(rargs) < nargs:
  1319.                 if nargs == 1:
  1320.                     self.error(_('%s option requires an argument') % opt)
  1321.                 else:
  1322.                     self.error(_('%s option requires %d arguments') % (opt, nargs))
  1323.             elif nargs == 1:
  1324.                 value = rargs.pop(0)
  1325.             else:
  1326.                 value = tuple(rargs[0:nargs])
  1327.                 del rargs[0:nargs]
  1328.         elif had_explicit_value:
  1329.             self.error(_('%s option does not take a value') % opt)
  1330.         else:
  1331.             value = None
  1332.         option.process(opt, value, values, self)
  1333.  
  1334.     
  1335.     def _process_short_opts(self, rargs, values):
  1336.         arg = rargs.pop(0)
  1337.         stop = False
  1338.         i = 1
  1339.         for ch in arg[1:]:
  1340.             opt = '-' + ch
  1341.             option = self._short_opt.get(opt)
  1342.             i += 1
  1343.             if not option:
  1344.                 raise BadOptionError(opt)
  1345.             option
  1346.             if option.takes_value():
  1347.                 if i < len(arg):
  1348.                     rargs.insert(0, arg[i:])
  1349.                     stop = True
  1350.                 
  1351.                 nargs = option.nargs
  1352.                 if len(rargs) < nargs:
  1353.                     if nargs == 1:
  1354.                         self.error(_('%s option requires an argument') % opt)
  1355.                     else:
  1356.                         self.error(_('%s option requires %d arguments') % (opt, nargs))
  1357.                 elif nargs == 1:
  1358.                     value = rargs.pop(0)
  1359.                 else:
  1360.                     value = tuple(rargs[0:nargs])
  1361.                     del rargs[0:nargs]
  1362.             else:
  1363.                 value = None
  1364.             option.process(opt, value, values, self)
  1365.             if stop:
  1366.                 break
  1367.                 continue
  1368.         
  1369.  
  1370.     
  1371.     def get_prog_name(self):
  1372.         if self.prog is None:
  1373.             return os.path.basename(sys.argv[0])
  1374.         return self.prog
  1375.  
  1376.     
  1377.     def expand_prog_name(self, s):
  1378.         return s.replace('%prog', self.get_prog_name())
  1379.  
  1380.     
  1381.     def get_description(self):
  1382.         return self.expand_prog_name(self.description)
  1383.  
  1384.     
  1385.     def exit(self, status = 0, msg = None):
  1386.         if msg:
  1387.             sys.stderr.write(msg)
  1388.         
  1389.         sys.exit(status)
  1390.  
  1391.     
  1392.     def error(self, msg):
  1393.         """error(msg : string)
  1394.  
  1395.         Print a usage message incorporating 'msg' to stderr and exit.
  1396.         If you override this in a subclass, it should not return -- it
  1397.         should either exit or raise an exception.
  1398.         """
  1399.         self.print_usage(sys.stderr)
  1400.         self.exit(2, '%s: error: %s\n' % (self.get_prog_name(), msg))
  1401.  
  1402.     
  1403.     def get_usage(self):
  1404.         if self.usage:
  1405.             return self.formatter.format_usage(self.expand_prog_name(self.usage))
  1406.         return ''
  1407.  
  1408.     
  1409.     def print_usage(self, file = None):
  1410.         '''print_usage(file : file = stdout)
  1411.  
  1412.         Print the usage message for the current program (self.usage) to
  1413.         \'file\' (default stdout).  Any occurence of the string "%prog" in
  1414.         self.usage is replaced with the name of the current program
  1415.         (basename of sys.argv[0]).  Does nothing if self.usage is empty
  1416.         or not defined.
  1417.         '''
  1418.         if self.usage:
  1419.             print >>file, self.get_usage()
  1420.         
  1421.  
  1422.     
  1423.     def get_version(self):
  1424.         if self.version:
  1425.             return self.expand_prog_name(self.version)
  1426.         return ''
  1427.  
  1428.     
  1429.     def print_version(self, file = None):
  1430.         '''print_version(file : file = stdout)
  1431.  
  1432.         Print the version message for this program (self.version) to
  1433.         \'file\' (default stdout).  As with print_usage(), any occurence
  1434.         of "%prog" in self.version is replaced by the current program\'s
  1435.         name.  Does nothing if self.version is empty or undefined.
  1436.         '''
  1437.         if self.version:
  1438.             print >>file, self.get_version()
  1439.         
  1440.  
  1441.     
  1442.     def format_option_help(self, formatter = None):
  1443.         if formatter is None:
  1444.             formatter = self.formatter
  1445.         
  1446.         formatter.store_option_strings(self)
  1447.         result = []
  1448.         result.append(formatter.format_heading(_('Options')))
  1449.         formatter.indent()
  1450.         if self.option_list:
  1451.             result.append(OptionContainer.format_option_help(self, formatter))
  1452.             result.append('\n')
  1453.         
  1454.         for group in self.option_groups:
  1455.             result.append(group.format_help(formatter))
  1456.             result.append('\n')
  1457.         
  1458.         formatter.dedent()
  1459.         return ''.join(result[:-1])
  1460.  
  1461.     
  1462.     def format_epilog(self, formatter):
  1463.         return formatter.format_epilog(self.epilog)
  1464.  
  1465.     
  1466.     def format_help(self, formatter = None):
  1467.         if formatter is None:
  1468.             formatter = self.formatter
  1469.         
  1470.         result = []
  1471.         if self.usage:
  1472.             result.append(self.get_usage() + '\n')
  1473.         
  1474.         if self.description:
  1475.             result.append(self.format_description(formatter) + '\n')
  1476.         
  1477.         result.append(self.format_option_help(formatter))
  1478.         result.append(self.format_epilog(formatter))
  1479.         return ''.join(result)
  1480.  
  1481.     
  1482.     def _get_encoding(self, file):
  1483.         encoding = getattr(file, 'encoding', None)
  1484.         if not encoding:
  1485.             encoding = sys.getdefaultencoding()
  1486.         
  1487.         return encoding
  1488.  
  1489.     
  1490.     def print_help(self, file = None):
  1491.         """print_help(file : file = stdout)
  1492.  
  1493.         Print an extended help message, listing all options and any
  1494.         help text provided with them, to 'file' (default stdout).
  1495.         """
  1496.         if file is None:
  1497.             file = sys.stdout
  1498.         
  1499.         encoding = self._get_encoding(file)
  1500.         file.write(self.format_help().encode(encoding, 'replace'))
  1501.  
  1502.  
  1503.  
  1504. def _match_abbrev(s, wordmap):
  1505.     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1506.  
  1507.     Return the string key in 'wordmap' for which 's' is an unambiguous
  1508.     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
  1509.     'words', raise BadOptionError.
  1510.     """
  1511.     if s in wordmap:
  1512.         return s
  1513.     possibilities = _[1]
  1514.     if len(possibilities) == 1:
  1515.         return possibilities[0]
  1516.     if not possibilities:
  1517.         raise BadOptionError(s)
  1518.     possibilities
  1519.     possibilities.sort()
  1520.     raise AmbiguousOptionError(s, possibilities)
  1521.  
  1522. make_option = Option
  1523.